﻿using System;
using System.Collections.Generic;
using System.Linq;
using Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Interface;


namespace OpenAuth.App
{
    public class InspectRecordApp : BaseApp<InspectRecord>
    {
        private RevelanceManagerApp _revelanceApp;
        private IAuth _auth;

        /// <summary>
        /// 加载列表
        /// </summary>
        public TableData Load(QueryInspectRecordListReq request)
        {
            var loginContext = _auth.GetCurrentUser();
            if (loginContext == null)
            {
                throw new CommonException("登录已过期", Define.INVALID_TOKEN);
            }

            var properties = loginContext.GetProperties("InspectRecord");

            if (properties == null || properties.Count == 0)
            {
                throw new Exception("当前登录用户没有访问该模块字段的权限，请联系管理员配置");
            }

            List<string> orgIdList = new List<string>();
            if (!string.IsNullOrEmpty(request.orgId))
            {
                var org = loginContext.Orgs.SingleOrDefault(u => u.Id == request.orgId);
                foreach (Org item in loginContext.Orgs)
                {
                    if (item.CascadeId.Contains(org.CascadeId))
                    {
                        orgIdList.Add(item.Id);
                    }
                }
            }
            else
            {
                orgIdList = loginContext.Orgs.Select(u => u.Id).ToList();
            }


            var result = new TableData();
            var objs = UnitWork.Find<InspectRecord>(u => orgIdList.Contains(u.OrgId));
            if (!string.IsNullOrEmpty(request.planId))
            {
                objs = objs.Where(u => u.InspectPlanId == request.planId);
            }
            if (!string.IsNullOrEmpty(request.startDate) && !string.IsNullOrEmpty(request.endDate))
            {
                DateTime startTime = Convert.ToDateTime(request.startDate);
                DateTime endTime = Convert.ToDateTime(request.endDate).AddDays(1).AddSeconds(-1);
                objs = objs.Where(u => u.StartTime > startTime && u.EndTime < endTime);
            }


            var propertyStr = string.Join(',', properties.Select(u => u.Key));
            result.columnHeaders = properties;
            result.data = objs.OrderByDescending(u => u.UploadTime)
                .Skip((request.page - 1) * request.limit)
                .Take(request.limit).Select($"new ({propertyStr})");
            result.count = objs.Count();
            return result;
        }

        public InspectRecordView GetDetail(string id)
        {
            var result = UnitWork.Find<InspectRecord>(u => u.Id == id)
                .Include(u => u.InspectRecordItems)
                    .ThenInclude(u => u.InspectArea)
                .Include(u => u.InspectRecordItems)
                    .ThenInclude(u => u.EquipmentInventory)
                .Include(u => u.InspectRecordItems)
                    .ThenInclude(u => u.InspectStandardItems)
                .Include(u => u.InspectPlan)
                .Include(u => u.User)
                .Include(u=>u.InspectSchedule)
                .First();
            result.InspectRecordItems = result.InspectRecordItems.OrderBy(u => u.InspectAreaId)
                .ThenBy(u => u.EquipmentInventoryId).ThenBy(u=>u.InspectStandardItems.Sort).ToList();
            var fileIds = result.InspectRecordItems.Select(u => u.FileIds).ToList();
            var files = UnitWork.Find<UploadFile>(u => fileIds.Contains(u.FileGuid));
            var recordView = new InspectRecordView()
            {
                InspectRecord = result,
                UploadFiles = files.ToList()
            };
            return recordView;
        }

        public void Update(InspectRecord obj)
        {
            UnitWork.Update<InspectRecord>(u => u.Id == obj.Id, u => new InspectRecord
            {
                //todo:要修改的字段赋值
            });

        }

        public InspectRecordApp(IUnitWork unitWork, IRepository<InspectRecord> repository,
            RevelanceManagerApp app, IAuth auth) : base(unitWork, repository)
        {
            _revelanceApp = app;
            _auth = auth;
        }
    }
}